
from django.shortcuts import render
from django.views import View
# Create your views here.
from django_redis import get_redis_connection

from celery_tasks.sms import constants
from meiduo_mall.libs.captcha.captcha import *
# from django_redis import get_redis_connection
from django import http

from meiduo_mall.utils.response_code import RETCODE

from random import randint
import logging
logger = logging.getLogger('django')

from . import *

from meiduo_mall.libs.yuntongxun.sms import CCP


from celery_tasks.sms.tasks import send_sms_code

class ImageCodeView(View):
    # 图形验证
    def get(self,request, uuid):
        # 使用SDK 生成图形验证码
        # name: 唯一标识
        # text: 图形验证码中的字符内容
        # image_bytes: 图片bytes类型数据
        name, text, image_bytes = captcha.generate_captcha()
        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_code')
        # 把图形验证码字符内容存储到redis中  # 为下后面发短信验证码时,可以进行校
        redis_conn.setex(uuid, 300, text)
        return http.HttpResponse(image_bytes,content_type='image/png')




class SMSCodeView(View):
        # 短信码验证
    def get(self, request, mobile):
        image_code_client = request.GET.get("image_code")
        uuid = request.GET.get("uuid")
        # 校验参数
        if all([image_code_client, uuid]) is False:

            return http.JsonResponse({'code':RETCODE.NECESSARYPARAMERR, 'errmsg':'缺少必要的参数'})
        # 创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')
        # 获取此手机号是否发送过短信标记
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code':RETCODE.THROTTLINGERR,'errmsg':'频繁发送短信'})
        # 提取图形验证码
        image_code_server = redis_conn.get(uuid)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR, 'ERRMSG':'图形验证码失效'})
        # 删除图形验证码，避免恶意测试图形验证码
        redis_conn.delete(uuid)

            # 对比图形验证码
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR, 'errmsg':'输入图形验证码有误'})


        # 生成短信验证码：生成6位i有效数字
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        print(sms_code)
        # # 保存短信验证码
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_EXPIRE_REDIS, sms_code)
        # # 重新写入send_flag
        # redis_conn.setex('send_flag_%s' %mobile, 60,1)
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_EXPIRE_REDIS, sms_code)
        pl.setex('send_flag_%s' %mobile, 60,1)
        pl.execute()
        # 发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_EXPIRE_REDIS//60], 1)
        send_sms_code.delay(mobile, sms_code)
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':"发送短信"})